package com.gitee.lw114514.tliasweb.exception;

import com.gitee.lw114514.tliasweb.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice //@RestControllerAdvice=@ControllerAdvice+@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常：", e);
        return Result.error("服务器发生异常");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("服务器发生异常：", e);
        String msg = e.getMessage();
        int i = msg.indexOf("Duplicate");
        msg = msg.substring(i);
        String[] split = msg.split(" ");
        String repeat = split[2];
        return Result.error(repeat + "已存在");
    }
}
